<template>
  <div>
    <div class="dice" ref="dice1">
      <span>{{ dice1Value }}</span>
    </div>
    <div class="dice" ref="dice2">
      <span>{{ dice2Value }}</span>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      dice1Value: '?',
      dice2Value: '?',
      intervalId1: null,
      intervalId2: null,
      rollDuration: 1000,
    }
  },
  methods: {
    getRandomNumber (min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min
    },
    startRolling (diceRef) {
      return setInterval(() => {
        const value = this.getRandomNumber(1, 6)
        if (diceRef === this.$refs.dice1) {
          this.dice1Value = value
        } else if (diceRef === this.$refs.dice2) {
          this.dice2Value = value
        }
      }, 100)
    },
    rollDice () {
      // 清除之前的轮播
      clearInterval(this.intervalId1)
      clearInterval(this.intervalId2)
      // 开始轮播数字
      this.intervalId1 = this.startRolling(this.$refs.dice1)
      this.intervalId2 = this.startRolling(this.$refs.dice2)
      // 1 秒后停止轮播并显示最终结果
      setTimeout(() => {
        clearInterval(this.intervalId1)
        clearInterval(this.intervalId2)
        this.dice1Value = this.getRandomNumber(1, 6)
        this.dice2Value = this.getRandomNumber(1, 6)
      }, this.rollDuration)
    },
  },
  mounted () {
    this.$el.addEventListener('click', this.rollDice)
  },
  beforeDestroy () {
    this.$el.removeEventListener('click', this.rollDice)
    clearInterval(this.intervalId1)
    clearInterval(this.intervalId2)
  },
}
</script>

<style>
.dice {
  width: 200px;
  height: 200px;
  background-color: white;
  border: 2px solid black;
  border-radius: 10px;
  display: block;
  text-align: center;
  line-height: 200px;
  font-size: 8em;
  margin: 20px auto;
  position: relative;
}

.dice span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}
</style>
